from flask import Blueprint, jsonify, request
import oss2

upload_bp = Blueprint('upload', __name__)

# 阿里云 OSS 配置
OSS_ENDPOINT = 'oss-cn-beijing.aliyuncs.com'
OSS_BUCKET = 'izumi-yuu'
OSS_ACCESS_KEY_ID = 'LTAI5tC5tDanBxi8t73xdnvc'
OSS_ACCESS_KEY_SECRET = 'wrF7YBMQtKzaG2gE7a5nISVXBUIFeG'

@upload_bp.route('/upload', methods=['POST'])
def upload():
    if 'file' not in request.files:
        return jsonify({"code": 400, "msg": "未检测到文件"}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({"code": 400, "msg": "文件名为空"}), 400
    # 上传到阿里云 OSS
    auth = oss2.Auth(OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET)
    bucket = oss2.Bucket(auth, OSS_ENDPOINT, OSS_BUCKET)
    oss_path = f"uploads/{file.filename}"
    bucket.put_object(oss_path, file.stream)
    url = f"https://{OSS_BUCKET}.oss-cn-beijing.aliyuncs.com/{oss_path}"
    return jsonify({"code": 0, "msg": "上传成功", "url": url})
